<!-- 服务政策  -->
<template>
  <div class="w-[100%] h-[100%]">
    <ContentWrap :show-border="false">
      <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="-mb-15px search-form"
        label-width="68px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="queryParams.name"
            class="!w-240px"
            clearable
            placeholder="请输入分类名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item class="p-0 m-0" style="border: none !important">
          <el-button @click="handleQuery" type="primary" color="#3721FF"> 搜索 </el-button>
          <el-button class="border-none" @click="resetQuery">
            <Icon class="mr-5px" icon="ant-design:clear-outlined" />
            清除条件
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap :show-border="false">
      <el-row :gutter="10">
        <el-col :span="1.5" class="el-btn">
          <el-button
            type="primary"
            color="#3721FF"
            class="add-website-btn"
            @click="handleAddWebservicepolicy"
          >
            <Icon class="mr-2px" icon="ep:plus" />
            新增政策
          </el-button>
        </el-col>
        <el-col :span="1.5" style="display: flex; align-items: center">
          <div class="text-xs text-[#3721FF] font-size-16px">了解服务政策</div>
        </el-col>
      </el-row>
    </ContentWrap>
    <ContentWrap :show-border="false">
      <el-table
        v-loading="loading"
        :data="list"
        :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#333' }"
        class="rounded-lg"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="分类名称" width="200" prop="name" />
        <el-table-column
          align="center"
          label="地区"
          min-width="90"
          prop="area"
          :filters="regionFiltersAdress"
          :filter-method="filterHandler"
        >
          <template #filter-icon>
            <Icon class="ml-2px" icon="ic:baseline-filter-alt" />
          </template>
          <!-- 自定义筛选弹窗内容 -->
          <template #filter="{ column }">
            <div class="custom-filter-panel">
              <!-- 搜索框 -->
              <el-input
                v-model="searchText"
                placeholder="搜索地区"
                clearable
                size="small"
                style="margin-bottom: 10px"
              />

              <!-- 筛选选项列表 -->
              <div style="max-height: 200px; overflow-y: auto">
                <el-checkbox-group v-model="selectedRegions">
                  <el-checkbox
                    v-for="item in filteredOptions(column.filters)"
                    :key="item.value"
                    :label="item.value"
                    style="display: block; margin: 5px 0"
                  >
                    {{ item.text }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="语言"
          min-width="90"
          prop="language"
          :filters="regionFiltersLanguage"
          :filter-method="filterHandler"
        >
          <template #filter-icon>
            <Icon class="ml-2px" icon="ic:baseline-filter-alt" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="创建者" prop="nickName" width="180" />
        <el-table-column
          :formatter="dateFormatter"
          align="center"
          label="创建时间"
          prop="createTime"
          width="180"
        />
        <el-table-column align="center" fixed="right" label="操作" class-name="all-button">
          <template #default="{ row }">
            <el-button link type="primary" color="#3721FF" plain @click="openForm(row.id)">
              编辑
            </el-button>
            <el-button link type="primary" color="#3721FF" plain @click="goCopy(row.id)">
              复制
            </el-button>
            <el-button link type="primary" color="#3721FF" plain @click="goDelete(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
    <AddWebservicepolicy
      v-if="isWebservicepolicy"
      :isWebservicepolicy="isWebservicepolicy"
      @close="isWebservicepolicy = false"
      :selectedId="selectedId"
      @refresh="getList"
      :isAddCopy="isAddCopy"
      ref="addWebservicepolicyRef"
    />
  </div>
  <!-- 正常删除弹窗 -->
  <ComfirmPops
    ref="deletePopsRef"
    :show-icon="true"
    width="500px"
    :show-dot="false"
    type="idTips"
    title="删除"
    :id="selectedId"
    @confirm="getDeletePops"
  >
    <template #content>
      <p>确定删除吗？</p>
    </template>
  </ComfirmPops>
</template>
<script lang="ts" setup>
import { TabsPaneContext } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import { dateFormatter } from '@/utils/formatTime'
import AddWebservicepolicy from './addWebservicepolicy.vue'
import { defaultProps, handleTree, treeToString } from '@/utils/tree'
import { ProductSpuStatusEnum } from '@/utils/constants'
import { fenToYuan } from '@/utils'
import download from '@/utils/download'
import { handlegetLanguageList, handleGetGlobeState } from '@/utils/index'
// import * as ProductSpuApi from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { WebServicePolicyApi } from '@/api/website/webservicepolicy'
defineOptions({ name: 'ServicePolicy' })
const addWebservicepolicyRef = ref()
const message = useMessage() // 消息弹窗
const route = useRoute() // 路由
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转
const selectedId = ref<number>() // 已选中的ID
const loading = ref(false) // 列表的加载中
const exportLoading = ref(false) // 导出的加载中
const total = ref(0) // 列表的总页数
const deletePopsRef = ref() // 删除弹窗的ref
const isAddCopy = ref(false) // 是否复制
const copyId = ref(0) // 复制的ID
const list = ref<ProductSpuApi.Spu[]>([]) // 列表的数据
const isWebservicepolicy = ref(false) // 是否新增网站组件
// tabs 数据
const tabsData = ref([
  {
    name: '出售中',
    type: 0,
    count: 0
  },
  {
    name: '仓库中',
    type: 1,
    count: 0
  },
  {
    name: '已售罄',
    type: 2,
    count: 0
  },
  {
    name: '警戒库存',
    type: 3,
    count: 0
  },
  {
    name: '回收站',
    type: 4,
    count: 0
  }
])
// 原始数据
const tableData = ref([{ region: '北京' }, { region: '上海' }, { region: '广州' }])

// 所有可筛选的地区选项
const regionFiltersAdress = ref([])
const regionFiltersLanguage = ref([])
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  tabType: 0,
  name: '',
  categoryId: undefined,
  createTime: undefined
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref

// 搜索关键词
const searchText = ref('')
// 已选中的地区
const selectedRegions = ref([])
const router = useRouter() // 路由

const goSetNavigation = () => {
  router.push({ name: 'SetNavigation' })
}
// 删除
const goDelete = (id: number) => {
  selectedId.value = id
  deletePopsRef.value.show()
}
// 复制
const goCopy = (id: number) => {
  isWebservicepolicy.value = true
  isAddCopy.value = true
  selectedId.value = id
}
//
const getDeletePops = async (bool,id: number) => {
  WebServicePolicyApi.deleteWebServicePolicy(id).then((res) => {
    message.success('删除成功')
    getList()
  })
}
// 根据搜索词过滤选项
const filteredOptions = (filters) => {
  return filters.filter((item) => item.text.includes(searchText.value))
}
const handleAddWebservicepolicy = () => {
  selectedId.value = undefined
  addWebservicepolicyRef.value?.resetForm()
  isWebservicepolicy.value = true
  isAddCopy.value = false
}
// 筛选逻辑
const filterHandler = (value: string, row: any, column: TableColumnCtx<any>) => {
  const property = column['property']
  return row[property] === value
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WebServicePolicyApi.getWebServicePolicyPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 切换 Tab */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.value.tabType = tab.paneName as number
  getList()
}

/** 获得每个 Tab 的数量 */
// const getTabsCount = async () => {
//   const res = await ProductSpuApi.getTabsCount()
//   for (let objName in res) {
//     tabsData.value[Number(objName)].count = res[objName]
//   }
// }

/** 添加到仓库 / 回收站的状态 */
// const handleStatus02Change = async (row: any, newStatus: number) => {
//   try {
//     // 二次确认
//     const text = newStatus === ProductSpuStatusEnum.RECYCLE.status ? '加入到回收站' : '恢复到仓库'
//     await message.confirm(`确认要"${row.name}"${text}吗？`)
//     // 发起修改
//     await ProductSpuApi.updateStatus({ id: row.id, status: newStatus })
//     message.success(text + '成功')
//     // 刷新 tabs 数据
//     await getTabsCount()
//     // 刷新列表
//     await getList()
//   } catch {}
// }

/** 更新上架/下架状态 */
// const handleStatusChange = async (row: any) => {
//   try {
//     // 二次确认
//     const text = row.status ? '上架' : '下架'
//     await message.confirm(`确认要${text}"${row.name}"吗？`)
//     // 发起修改
//     await ProductSpuApi.updateStatus({ id: row.id, status: row.status })
//     message.success(text + '成功')
//     // 刷新 tabs 数据
//     await getTabsCount()
//     // 刷新列表
//     await getList()
//   } catch {
//     // 异常时，需要重置回之前的值
//     row.status =
//       row.status === ProductSpuStatusEnum.DISABLE.status
//         ? ProductSpuStatusEnum.ENABLE.status
//         : ProductSpuStatusEnum.DISABLE.status
//   }
// }

/** 删除按钮操作 */
// const handleDelete = async (id: number) => {
//   try {
//     // 删除的二次确认
//     await message.delConfirm()
//     // 发起删除
//     await ProductSpuApi.deleteSpu(id)
//     message.success(t('common.delSuccess'))
//     // 刷新tabs数据
//     await getTabsCount()
//     // 刷新列表
//     await getList()
//   } catch {}
// }

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 新增或修改 */
const openForm = (id?: number) => {
  isWebservicepolicy.value = true
  console.log(id)
  isAddCopy.value = false
  selectedId.value = id
}

/** 查看商品详情 */
const openDetail = (id: number) => {
  push({ name: 'ProductSpuDetail', params: { id } })
}

/** 导出按钮操作 */
// const handleExport = async () => {
//   try {
//     // 导出的二次确认
//     await message.exportConfirm()
//     // 发起导出
//     exportLoading.value = true
//     const data = await ProductSpuApi.exportSpu(queryParams.value)
//     download.excel(data, '商品列表.xls')
//   } catch {
//   } finally {
//     exportLoading.value = false
//   }
// }

/** 获取分类的节点的完整结构 */
const categoryList = ref() // 分类树
const formatCategoryName = (categoryId: number) => {
  return treeToString(categoryList.value, categoryId)
}

/** 激活时 */
onActivated(() => {
  getList()
})

/** 初始化 **/
onMounted(async () => {
  // 解析路由的 categoryId
  if (route.query.categoryId) {
    queryParams.value.categoryId = route.query.categoryId
  }
  let adress = await handleGetGlobeState()
  regionFiltersAdress.value = adress.map((item) => {
    return {
      ...item,
      text: item.label,
      value: item.label
    }
  })
  regionFiltersLanguage.value = await handlegetLanguageList()

  // 获得商品信息
  // await getTabsCount()
  await getList()
  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({})
  categoryList.value = handleTree(data, 'id', 'parentId')
})
</script>
<style scoped>
@import '@/styles/website.scss';
</style>
